package com.promise.jokerdream.work.signin.lucky

import com.promise.jokerdream.manager.ExecutionHistoryManager
import com.promise.jokerdream.repository.GameApi
import com.promise.jokerdream.utils.AppContext
import com.promise.jokerdream.work.BaseWork
import com.promise.jokerdream.work.WorkResult

// 吉利兑
class LuckyExchangeWork(uin: String): BaseWork(uin) {

    override val name: String
        get() = "吉利兑"

    override val priority: Int
        get() = 9

    override val isActWork: Boolean
        get() = true

    private val gameApi = GameApi.Companion.getInstance()
    private val historyManager by lazy { ExecutionHistoryManager.Companion.getInstance(AppContext.get()) }

    override suspend fun executeWork(): WorkResult {
        // 查询吉利兑信息
        val queryResult = gameApi.queryLuckyExchange()
        return queryResult.fold(
            onSuccess = { response ->
                // 检查任务列表中的奖励
                response.task.forEach { gift ->
                    if (gift.status == 1) {
                        val rewardResult = gameApi.rewardLuckyExchange(gift.taskId)
                        rewardResult.fold(
                            onSuccess = { rewardResponse ->
                                historyManager.addHistory(name, rewardResponse.getDescription())
                            },
                            onFailure = { exception ->
                                historyManager.addHistory(name, exception.message)
                            }
                        )
                    }
                }

                WorkResult.Success
            },
            onFailure = { exception ->
                historyManager.addHistory(name, exception.message)
                WorkResult.Failure(exception, exception.message)
            }
        )
    }
}